package com.ls.common.exception;

import com.ls.common.entity.Result;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;



@ControllerAdvice
public class GlobalException {

    private static final Logger logger = LoggerFactory.getLogger(GlobalException.class);


    // 业务异常
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result BusinessExceptionHandler(BusinessException ex) {
        if (ex.getCode() != -1) {
            logger.error("code : " + ex.getCode() + " msg : " + ex.getMessage(), ex);
        }
        if(StringUtils.isBlank(ex.getLocalizedMessage())||StringUtils.isBlank(ex.getMessage())){
            return new Result(500, "服务器异常");
        }
        return new Result(ex.getCode(), ex.getMessage());
    }



    // java异常异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result ExceptionHandler(Exception ex) {
        logger.error( " msg : " + ex.getMessage(), ex);
        if(StringUtils.isBlank(ex.getLocalizedMessage())){
            return new Result(500, "服务器异常");
        }
        return new Result(500,ex.getMessage());
    }

}
